package com.jhgk.jhcee.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgk.jhcee.common.enums.BasisResultEnum;
import com.jhgk.jhcee.common.resultful.BasisResultful;
import com.jhgk.jhcee.data.auth.entity.SysUserOrgRelation;
import com.jhgk.jhcee.data.auth.mapper.SysUserOrgRelationMapper;
import com.jhgk.jhcee.system.service.SysUserOrgRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: lemon_xzp
 * @Date: 2021/9/30 17:24
 */
@Service(value = "SysUserOrgRelationServiceImpl")
public class SysUserOrgRelationServiceImpl extends ServiceImpl<SysUserOrgRelationMapper, SysUserOrgRelation> implements SysUserOrgRelationService {

    @Autowired
    SysUserOrgRelationMapper sysUserOrgRelationMapper;

    @Override
    public BasisResultful<Object> addRelation(Long userId, Long orgId) {
        if (null == userId || null == orgId) {
            return BasisResultful.fail(BasisResultEnum.PARAM_IS_NULL);
        }
        // 查询关系是否存在
        QueryWrapper<SysUserOrgRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("org_id", orgId);
        SysUserOrgRelation sysUserOrgRelation = sysUserOrgRelationMapper.selectOne(wrapper);
        if (null == sysUserOrgRelation) {
            sysUserOrgRelation = new SysUserOrgRelation();
            sysUserOrgRelation.setUserId(userId);
            sysUserOrgRelation.setOrgId(orgId);
            boolean b = this.saveOrUpdate(sysUserOrgRelation);
            return b ? BasisResultful.success() : BasisResultful.fail();
        }
        return BasisResultful.success();
    }

    @Override
    public BasisResultful<Object> delRelation(Long userId, Long orgId) {
        if (null == userId || null == orgId) {
            return BasisResultful.fail(BasisResultEnum.PARAM_IS_NULL);
        }
        QueryWrapper<SysUserOrgRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("org_id", orgId);
        sysUserOrgRelationMapper.delete(wrapper);
        return BasisResultful.success();
    }

    @Override
    public BasisResultful<Object> updateRelation(Long userId, Long orgId) {
        if (null == userId || null == orgId) {
            return BasisResultful.fail(BasisResultEnum.PARAM_IS_NULL);
        }
        QueryWrapper<SysUserOrgRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        SysUserOrgRelation sysUserOrgRelation = sysUserOrgRelationMapper.selectOne(wrapper);
        if (null == sysUserOrgRelation) {
            sysUserOrgRelation = new SysUserOrgRelation();
        }
        sysUserOrgRelation.setUserId(userId);
        sysUserOrgRelation.setOrgId(orgId);
        this.saveOrUpdate(sysUserOrgRelation);
        return BasisResultful.success();
    }
}
